﻿using System.Diagnostics;

namespace RndMaterialDisposalService.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public class ResponseMiddleware
    {

        private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms";

        private readonly RequestDelegate _next;
        private readonly ILogger<ResponseMiddleware> _logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        /// <param name="logger"></param>
        public ResponseMiddleware(RequestDelegate next, ILogger<ResponseMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Path.Value!.StartsWith("/api"))
            {
                long responseTimeForCompleteRequest = 0;
                var watch = new Stopwatch();
                watch.Start();
                context.Response.OnStarting(() =>
                {
                    watch.Stop();
                    responseTimeForCompleteRequest = watch.ElapsedMilliseconds;
                    context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString();
                    var url = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
                    _logger.LogTrace($"请求Url:{url} 耗时:{responseTimeForCompleteRequest}毫秒");
                    //var response = context.Response.bod;
                    //context.Response.WriteAsJsonAsync(url);
                    return Task.CompletedTask;
                });
            }
            return this._next(context);
        }

    }
}
